//
//  DeliveryAddressViewController.m
//  xpkc
//
//  Created by TopSageOSX on 14/12/27.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "DeliveryAddressViewController.h"
#import "NewAddressViewController.h"

#import "UserMessage.h"

#import "DeliveryAddressTableViewCell.h"

#import "DeliveryAddressModel.h"

#import "DeliveryView.h"

#import "MBProgressHUD.h"

@interface DeliveryAddressViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    
    NSMutableArray * _addressArray;
    
    DeliveryAddressModel * _deliveryModel;
    
    DeliveryAddressModel * _currentModel;
    
    NSIndexPath * _indexPath;
    
    
    DeliveryView * _deliveryView;
    
    NSArray * _array;
    NSDictionary * _dict;
    
    NSMutableArray * _defaultAddressArray;
    
    NSMutableIndexSet * _selectIndexSet;
    
    NSInteger _index;
    
    
}
@end

@implementation DeliveryAddressViewController


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [_addressArray removeAllObjects];
    [self createDataSource];
    [_selectIndexSet removeAllIndexes];
    [_deliveryView.cartTable reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    self.title = @"收货地址";
    self.view.backgroundColor = [UIColor whiteColor];
    _addressArray = [NSMutableArray array];
    _defaultAddressArray = [[NSMutableArray alloc] init];
    
    [self createTableView];
    
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/4, SCREEN_HEIGHT-50-64, SCREEN_WIDTH/2, 50)];
    button.backgroundColor=[UIColor redColor];
    [button setTitle:@"+新添加收货地址" forState:(UIControlStateNormal)];
    [button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    button.titleLabel.font=[UIFont boldSystemFontOfSize:19];
    [self.view addSubview:button];
    [button addTarget:self action:@selector(buttonClick) forControlEvents:(UIControlEventTouchUpInside)];
}

// 获取我的收货地址列表
-(void) createDataSource{
    
    NSString *module = @"address";
    NSString *interface = @"myaddress";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"userid":[UserMessage sharedUserMessage].userMid,@"pagecode":@"1"};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    
    
    //    NSLog(@"urlstring--%@",urlString);
    //    NSLog(@"parameter--%@",parameter);
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        logdebug(@"%@",dic);
        NSArray * infoArray = dic[@"info"];
        
        _array = infoArray;
        for (NSDictionary * subDic in infoArray) {
            
            NSLog(@"%@",subDic);
            
            if ([subDic[@"isdefault"] intValue]) {
                
                [[NSUserDefaults standardUserDefaults] setValue:subDic forKey:@"defaultAddressKey"];
                
            }
            
            DeliveryAddressModel * deliveryAddressModel = [DeliveryAddressModel deliveryAddressModelWithDict:subDic];
            
            [_addressArray addObject:deliveryAddressModel];
            
            
        }
        
        
        [_deliveryView.cartTable reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //
        
        NSLog(@"%@",error);
    }];
    
    
}

#pragma mark dataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    // NSLog(@"%d",_addressArray.count);
    return 1;
    
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _addressArray.count;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
    
}

-(void)dele:(UIButton *)btn{
    
    
    DeliveryAddressModel * model = _addressArray[btn.tag];
    NSLog(@"%@,---btn.tag = %ld--%ld",model.address,btn.tag,_addressArray.count);
    _index = btn.tag;
    
    NSLog(@"%ld",btn.tag);
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"确定删除？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    
    
    [alert show];
    
    
    
    
    
    
    //    NSString *module = @"address";
    //    NSString *interface = @"deladdress";
    //
    //    NSString *timeString = [GetTime getTime];
    //    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    //    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL,module,interface,hashString];
    //
    //    NSDictionary *parameter = @{@"time":timeString,@"uid":[UserMessage sharedUserMessage].userMid,@"id":model.codeId};
    //
    //    NSLog(@"%@",model.codeId);
    //    NSLog(@"URLSTRING--%@",urlString);
    //    NSLog(@"parameter--%@--%@",parameter,model.address);
    //    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
    //        logdebug(@"%@",dic);
    //
    //        if ([[dic objectForKey:@"succ"] intValue]) {
    //
    //            NSLog(@"succ");
    //
    //            [self performSelectorOnMainThread:@selector(deleteView) withObject:nil waitUntilDone:YES];
    //        }
    //
    //
    //    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //        //
    //        NSLog(@"%@",error);
    //        [self performSelectorOnMainThread:@selector(deleteView) withObject:nil waitUntilDone:YES];
    //    }];
    
    
}

-(void)edit:(UIButton *)btn{
    
    // NSLog(@"%ld",btn.tag);
    DeliveryAddressModel * model = _addressArray[btn.tag];
    
    NewAddressViewController * newaddress = [[NewAddressViewController alloc] init];
    
    newaddress.deliverymodel = model;
    NSLog(@"%@",model.address);
    [self.navigationController pushViewController:newaddress animated:YES];
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
}

-(void)deleteView{
    
    NSDictionary * addressDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"defaultAddressKey"];
    DeliveryAddressModel * model = _addressArray[_index];
    NSLog(@"%@--%@",addressDic[@"id"],model.codeId);
    NSLog(@"%@",_dict);
    NSLog(@"%@",model.codeId);
    
    if ([[NSString stringWithFormat:@"%@",addressDic[@"id"]] isEqualToString:model.codeId]) {
        
        [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:@"defaultAddressKey"];
        
    }
    
    
    [_addressArray removeObjectAtIndex:_index];
    //    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"删除成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    //
    //
    //    [alert show];
    //    DeliveryAddressModel * model = _addressArray[_index];
    NSLog(@"%ld",_index);
    
    [self.navigationController popViewControllerAnimated:YES];
    //
    //        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:_index inSection:0];
    ////     [_deliveryView.cartTable reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    //
    //    NSArray * array = [NSArray arrayWithObject:indexPath];
    //    NSLog(@"----%@",array);
    //    // [_deliveryView.cartTable reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationAutomatic];
    //
    //    [_deliveryView.cartTable reloadData];
    // [_deliveryView.cartTable deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    DeliveryAddressTableViewCell * deliveryCell = [tableView dequeueReusableCellWithIdentifier:@"delivery"];
    
    if (deliveryCell == nil) {
        
        deliveryCell = [[DeliveryAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"delivery"];
    }
    
    deliveryCell.viewController = self;
    
    deliveryCell.deleteBtn.tag = indexPath.row;
    [deliveryCell.deleteBtn addTarget:self action:@selector(dele:) forControlEvents:UIControlEventTouchUpInside];
    //    deliveryCell.editBtn.tag = indexPath.section;
    //    [deliveryCell.editBtn addTarget:self action:@selector(edit:) forControlEvents:UIControlEventTouchUpInside];
    
    __block DeliveryAddressModel * model = _addressArray[indexPath.row];
    
    
    [deliveryCell configCellWithDeliveryModel:model];
    
    __block NSArray * array;
    
    array = @[indexPath];
    
    _indexPath = indexPath;
    
    //    deliveryCell.myblock = ^(NSString * str){
    //
    //
    //        if ([str isEqualToString:@"delete"]) {
    //
    //            [_addressArray removeObject:model];
    //
    //        }
    //
    //
    //        [_deliveryView.cartTable reloadData];
    //
    //
    //    };
    
    return deliveryCell;
    
}



#pragma mark delegate

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 0;
    }
    
    return 20;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UILabel * headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    headLabel.backgroundColor = BGColor;
    
    return headLabel;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    [_selectIndexSet addIndex:indexPath.row];
    
    
    NSLog(@"---%ld",indexPath.row);
    _deliveryModel = _addressArray[indexPath.section];
    NSLog(@"%@",_array);
    _dict = _array[indexPath.row];
    
    for (int i = 0; i < _defaultAddressArray.count; i ++) {
        NSIndexPath * subIndex = _defaultAddressArray[i];
        [_defaultAddressArray removeObjectAtIndex:i];
        [_deliveryView.cartTable deselectRowAtIndexPath:subIndex animated:YES];
        
    }
    
    [_defaultAddressArray addObject:indexPath];
    
    [_deliveryView.cartTable selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    //    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    
    
}


-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    [_selectIndexSet removeIndex:indexPath.row];
    
    [_defaultAddressArray removeLastObject];
}

-(void)createTableView{
    
    
    
    _deliveryView = [[DeliveryView alloc]initWithFrame:self.view.bounds];
    _deliveryView.cartTable.delegate = self;
    _deliveryView.cartTable.dataSource = self;
    [_deliveryView.cartTable setEditing:YES animated:YES];
    //    [_deliveryView.selectAll addTarget:self action:@selector(selectAllItem:) forControlEvents:UIControlEventTouchUpInside];
    //    [_deliveryView.deleteBtn addTarget:self action:@selector(deleteRow:) forControlEvents:UIControlEventTouchUpInside];
    _deliveryView.cartTable.rowHeight = 140;
    _deliveryView.backgroundColor = BGColor;
    
    [_deliveryView.defaultAddressBtn addTarget:self action:@selector(defaultAddress:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_deliveryView];
    
    //    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    //    label.backgroundColor = BGColor;
    //
    //    _deliveryView.cartTable.tableFooterView = label;
    
}

- (void)getCartData{
    _selectIndexSet = [NSMutableIndexSet indexSet];
}

/**
 *  全选按钮
 *
 *  @param btn btn
 */
- (void)selectAllItem:(UIButton *)btn{
    if (btn.selected) {
        //取消全选
        for (int i = 0; i<_addressArray.count; i++) {
            NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
            [_deliveryView.cartTable deselectRowAtIndexPath:indexpath animated:YES];
        }
        
        
        [_selectIndexSet removeAllIndexes];
        btn.selected = NO;
    }else{
        
        for (int i = 0; i<_addressArray.count; i++) {
            NSIndexPath *indexpath = [NSIndexPath indexPathForRow:i inSection:0];
            [_deliveryView.cartTable selectRowAtIndexPath:indexpath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
            [_selectIndexSet addIndex:i];
            
            
        }
        btn.selected = YES;
    }
    
    
    
}


- (void)deleteRow:(UIButton *)btn{
    
    
    
    DeliveryAddressModel * model = _addressArray[btn.tag];
    NSLog(@"%@,---btn.tag = %ld--%ld",model.address,btn.tag,_addressArray.count);
    _index = btn.tag;
    
    [_addressArray removeObject:model];
    
    //    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:btn.tag];
    //[_deliveryView.cartTable reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    //    [_deliveryView.cartTable deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    
    
    //    NSLog(@"%@",_array[btn.tag]);
    NSString *module = @"address";
    NSString *interface = @"deladdress";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"uid":[UserMessage sharedUserMessage].userMid,@"id":model.codeId};
    
    //    NSLog(@"%@",model.codeId);
    //    NSLog(@"URLSTRING--%@",urlString);
    //    NSLog(@"parameter--%@--%@",parameter,model.address);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        logdebug(@"%@",dic);
        
        if ([[dic objectForKey:@"succ"] intValue]) {
            
            NSLog(@"succ");
            
            [self performSelectorOnMainThread:@selector(deleteView) withObject:nil waitUntilDone:YES];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //
        NSLog(@"%@",error);
    }];
    
    
    
    [_addressArray removeObjectsAtIndexes:_selectIndexSet];
    
    NSMutableArray *deleteArray = [NSMutableArray array];
    [_selectIndexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        
        
        //        NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        //        NSString *fileName=[doc stringByAppendingPathComponent:@"buy.sqlite"];
        //        FMDatabase * database =[FMDatabase databaseWithPath:fileName];
        //        [database open];
        //        NSString *deleteSql = [NSString stringWithFormat:@"delete from buy where name = '%@'",str];
        //        [database executeUpdate:deleteSql];
        //        [database close];
        
        // 删除操作
        
        
        NSIndexPath *indexpath = [NSIndexPath indexPathForRow:idx inSection:0];
        [deleteArray addObject:indexpath];
        
        
    }];
    
    [_deliveryView.cartTable deleteRowsAtIndexPaths:deleteArray withRowAnimation:UITableViewRowAnimationFade];
    [_selectIndexSet removeAllIndexes];
    // _deliveryView.selectAll.selected = NO;
    
    
}



// 设置默认收货地址
-(void)defaultAddress:(UIButton *)btn{
    
    
    if (_dict == nil) {
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"您还没选择地址" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    
    //    if (btn.selected) {
    //        //取消全选
    //
    //        btn.selected = NO;
    //    }else{
    //
    //        btn.selected = YES;
    //    }
    
    NSString *module = @"address";
    NSString *interface = @"defaultaddress";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    
    NSDictionary *parameter = @{@"time":timeString,@"uid":[UserMessage sharedUserMessage].userMid,@"id":_deliveryModel.codeId};
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //     manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    NSLog(@"99999----%@",urlString);
    NSLog(@"-----%@",parameter);
    
    
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //成功
        NSDictionary * userDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        //之后创建视图
        logdebug(@"%@",userDic);
        
        if ([userDic[@"succ"] intValue]) {
            
            
            
            [self performSelectorOnMainThread:@selector(setDefault:) withObject:userDic[@"succ"] waitUntilDone:YES];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self performSelectorOnMainThread:@selector(setDefault:) withObject:nil waitUntilDone:YES];
        //失败
        logdebug(@"%@",error.localizedDescription);
    }];
    
}


// 设置默认收货地址

-(void)setDefault:(NSString * )str{
    
    //    if ([str intValue]) {
    NSLog(@"默认地址：%@",_dict);
    [[NSUserDefaults standardUserDefaults] setObject:_dict forKey:@"defaultAddressKey"];
    
    [self.navigationController popViewControllerAnimated:YES];
    
    //    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"设置默认收货地址成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    //    [alert show];
    
    // NSLog(@"%@--%ld",_defaultAddressArray,_defaultAddressArray.count);
    
    
    //    }
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    if (buttonIndex == 0) {
        
        NSLog(@"%ld",_index);
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"删除中";
        
        DeliveryAddressModel * model = _addressArray[_index];
        
        NSString *module = @"address";
        NSString *interface = @"deladdress";
        
        NSString *timeString = [GetTime getTime];
        NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
        NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
        
        NSDictionary *parameter = @{@"time":timeString,@"uid":[UserMessage sharedUserMessage].userMid,@"id":model.codeId};
        
        NSLog(@"%@",model.codeId);
        NSLog(@"URLSTRING--%@",urlString);
        NSLog(@"parameter--%@--%@",parameter,model.address);
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            logdebug(@"%@",dic);
            
            if ([[dic objectForKey:@"succ"] intValue]) {
                
                NSLog(@"succ");
                
                [self performSelectorOnMainThread:@selector(deleteView) withObject:nil waitUntilDone:YES];
            }
            
            
            // [_deliveryView.cartTable reloadData];
            [hud hide:YES];
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //
            [hud hide:YES];
            NSLog(@"%@",error);
            [self performSelectorOnMainThread:@selector(deleteView) withObject:nil waitUntilDone:YES];
        }];
        
        
    }else{
        
        
    }
    
    
    
    
    
}

-(void)buttonClick
{
    NewAddressViewController * new =[[NewAddressViewController alloc] init];
    [self.navigationController pushViewController:new animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
